import time
import undetected_chromedriver as uc
import selenium
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


options = uc.ChromeOptions()
options.user_data_dir = "/Users/jinjiakk/应用程序文件/selenium/user"
driver_path = "/Users/jinjiakk/应用程序文件/selenium/chromedriver-mac-x64/chromedriver-mac-x64/chromedriver"
browser_path = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
# browser_path = "/Applications/Google Chrome.app"


class DFRobot(object):
    def __init__(self):
        self.driver = None
        # 启动浏览器
        self.launch_browser()

    def launch_browser(self):
        options = uc.ChromeOptions()
        options.user_data_dir = "/Users/jinjiakk/应用程序文件/selenium/user"
        driver_path = "/Users/jinjiakk/应用程序文件/selenium/chromedriver-mac-x64/chromedriver-mac-x64/chromedriver"
        browser_path = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
        driver = uc.Chrome(
            driver_executable_path=driver_path,
            browser_executable_path=browser_path,
            options=options,
            enable_cdp_events=True,
            port=53610
        )
        self.driver = driver
        return driver
    
    def load_file_link(self,file_url):
        self.driver.get(file_url)
        input('sss')
    
    def load_iframe(self):
        ele = self.driver.find_element(By.XPATH,".//iframe[@id='wiki-doc-iframe']")
        if ele:
            iframe_url = ele.get_attribute("src")
            print(iframe_url)
            self.driver.get(iframe_url)
    
    def down_load_file(self):
        element = WebDriverWait(self.driver, timeout=30,poll_frequency=0.5).until(
                        EC.visibility_of_any_elements_located((By.XPATH, ".//button[@data-testid='doc-header-more-button']"))
                    )
        print(element)
        input("b1")
        button1 = self.driver.find_element(By.XPATH,".//button[@data-testid='doc-header-more-button']")
        button1.click()

        input("b2")
        button2 = self.driver.find_element(By.XPATH,".//div[text()='下载到本地']")
        button2.click()

        input("b3")
        button3 = self.driver.find_element(By.XPATH,".//div[text()='Word(.docx)']")
        button3.click()

    def down_file(self,file_url):
        self.load_file_link(file_url)
        self.load_iframe()
        self.down_load_file()

if __name__ == "__main__":
    dfr = DFRobot()
    dfr.down_file(file_url='https://alidocs.dingtalk.com/i/nodes/a9E05BDRVQ6g5ookSjkgldNqJ63zgkYA?iframeQuery=utm_source%3Dportal%26utm_medium%3Dportal_recent&rnd=0.4790207999252444')

''' 
    文档中有图片是识别不到的
    产品文档要求中 需要判断 需求是否是跨产品的
    文档内容中又附了其他的钉钉文档 访问不了
'''